<template>
  <div class="admin-roles">
    <el-card class="table-card" v-loading="loading">
      <div class="table-header">
        <h3>角色列表</h3>
        <div class="meta">
          <el-button type="primary" @click="openCreate">新建角色</el-button>
          <el-input
            v-model="keyword"
            placeholder="输入角色名称关键词"
            clearable
            class="search-input"
            @keyup.enter.native="handleSearch"
          />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <span class="total">共 {{ total }} 条</span>
        </div>
      </div>
      <el-table :data="roleList" style="width: 100%">
        <el-table-column prop="roleId" label="角色ID" min-width="10%" />
        <el-table-column prop="roleName" label="角色名称" min-width="20%" />
        <el-table-column label="权限" min-width="40%">
          <template #default="scope">
            <template v-if="Array.isArray(scope.row.permissions) && scope.row.permissions.length">
              <el-space wrap>
                <el-tag
                  v-for="(p, idx) in scope.row.permissions"
                  :key="idx + '-' + p"
                  :type="getPermissionTagType(p)"
                >
                  {{ getPermissionText(p) }}
                </el-tag>
              </el-space>
            </template>
            <template v-else>
              <el-tag type="info">无</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="adminCount" label="管理员数量" min-width="15%" />
        <el-table-column label="操作" min-width="26%">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openDetail(scope.row)">详情</el-button>
            <el-button size="small" @click="openEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="confirmDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="角色详情" width="520px">
      <el-skeleton :loading="detailLoading" animated>
        <template #template>
          <el-skeleton-item variant="p" style="width: 60%" />
          <el-skeleton-item variant="p" style="width: 40%" />
          <el-skeleton-item variant="p" style="width: 80%" />
        </template>
        <template #default>
          <div v-if="roleDetail">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="角色ID">{{ roleDetail.roleId }}</el-descriptions-item>
              <el-descriptions-item label="角色名称">{{ roleDetail.roleName }}</el-descriptions-item>
              <el-descriptions-item label="管理员数量">{{ roleDetail.adminCount }}</el-descriptions-item>
              <el-descriptions-item label="权限">
                <el-space wrap>
                  <el-tag
                    v-for="(p, idx) in roleDetail.permissions || []"
                    :key="idx + '-' + p"
                    :type="getPermissionTagType(p)"
                  >
                    {{ getPermissionText(p) }}
                  </el-tag>
                </el-space>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </template>
      </el-skeleton>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新建角色弹窗 -->
    <el-dialog v-model="createVisible" title="新建角色" width="520px">
      <el-form :model="createForm" label-width="100px">
        <el-form-item label="角色名称" required>
          <el-input v-model="createForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限" required>
          <el-select v-model="createForm.permissions" multiple placeholder="请选择权限" style="width: 100%">
            <el-option
              v-for="opt in permissionsOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button type="primary" :loading="createLoading" @click="submitCreate">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑角色弹窗 -->
    <el-dialog v-model="editVisible" title="编辑角色" width="520px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="角色名称" required>
          <el-input v-model="editForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限" required>
          <el-select v-model="editForm.permissions" multiple placeholder="请选择权限" style="width: 100%">
            <el-option
              v-for="opt in permissionsOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdminRoleList, searchAdminRoles, getAdminRoleDetail, createAdminRole, updateAdminRole, deleteAdminRole } from '@/api/adminRole'

const loading = ref(false)
const roleList = ref([])
const total = ref(0)
const keyword = ref('')

const detailVisible = ref(false)
const detailLoading = ref(false)
const roleDetail = ref(null)

const createVisible = ref(false)
const createLoading = ref(false)
const createForm = ref({ roleName: '', permissions: [] })

const editVisible = ref(false)
const editLoading = ref(false)
const editForm = ref({ roleId: null, roleName: '', permissions: [] })

const permissionsOptions = [
  { value: 'all', label: '所有权限（超级权限）' },
  { value: 'manage_user', label: '用户管理权限' },
  { value: 'approve', label: '审核权限' },
  { value: 'matchmaking', label: '撮合权限' },
  { value: 'content_edit', label: '内容编辑权限' }
]

const getPermissionText = (code) => {
  const map = {
    all: '所有权限（超级权限）',
    manage_user: '用户管理权限',
    approve: '审核权限',
    matchmaking: '撮合权限',
    content_edit: '内容编辑权限'
  }
  return map[code] || code
}

const getPermissionTagType = (code) => {
  const typeMap = {
    all: 'danger',
    manage_user: 'warning',
    approve: 'success',
    matchmaking: 'primary',
    content_edit: 'info'
  }
  return typeMap[code] || 'info'
}

const fetchRoleList = async () => {
  loading.value = true
  try {
    const res = await getAdminRoleList()
    if (res && res.code === 200) {
      roleList.value = Array.isArray(res.data) ? res.data : []
      total.value = typeof res.total === 'number' ? res.total : roleList.value.length
    } else {
      ElMessage.error(res?.message || '获取角色列表失败')
    }
  } catch (err) {
    console.error('getAdminRoleList error:', err)
  } finally {
    loading.value = false
  }
}

const handleSearch = async () => {
  loading.value = true
  try {
    const res = await searchAdminRoles({ roleName: keyword.value })
    if (res && res.code === 200) {
      roleList.value = Array.isArray(res.data) ? res.data : []
      total.value = typeof res.total === 'number' ? res.total : roleList.value.length
    } else {
      ElMessage.error(res?.message || '搜索角色失败')
    }
  } catch (err) {
    console.error('searchAdminRoles error:', err)
  } finally {
    loading.value = false
  }
}

const handleReset = () => {
  keyword.value = ''
  fetchRoleList()
}

const openDetail = async (row) => {
  detailVisible.value = true
  detailLoading.value = true
  roleDetail.value = null
  try {
    const res = await getAdminRoleDetail(row.roleId)
    if (res && res.code === 200) {
      roleDetail.value = res.data || null
    } else {
      ElMessage.error(res?.message || '获取角色详情失败')
    }
  } catch (err) {
    console.error('getAdminRoleDetail error:', err)
  } finally {
    detailLoading.value = false
  }
}

const openCreate = () => {
  createForm.value = { roleName: '', permissions: [] }
  createVisible.value = true
}

const submitCreate = async () => {
  if (!createForm.value.roleName || !createForm.value.permissions.length) {
    ElMessage.error('请填写角色名称并选择权限')
    return
  }
  createLoading.value = true
  try {
    const res = await createAdminRole(createForm.value)
    if (res && res.code === 200) {
      ElMessage.success(res.message || '角色创建成功')
      createVisible.value = false
      fetchRoleList()
    } else {
      ElMessage.error(res?.message || '角色创建失败')
    }
  } catch (err) {
    console.error('createAdminRole error:', err)
  } finally {
    createLoading.value = false
  }
}

const openEdit = (row) => {
  editForm.value = {
    roleId: row.roleId,
    roleName: row.roleName,
    permissions: Array.isArray(row.permissions) ? [...row.permissions] : []
  }
  editVisible.value = true
}

const submitEdit = async () => {
  if (!editForm.value.roleName || !editForm.value.permissions.length) {
    ElMessage.error('请填写角色名称并选择权限')
    return
  }
  editLoading.value = true
  try {
    const res = await updateAdminRole(editForm.value.roleId, {
      roleName: editForm.value.roleName,
      permissions: editForm.value.permissions
    })
    if (res && res.code === 200) {
      ElMessage.success(res.message || '角色更新成功')
      editVisible.value = false
      fetchRoleList()
    } else {
      ElMessage.error(res?.message || '角色更新失败')
    }
  } catch (err) {
    console.error('updateAdminRole error:', err)
  } finally {
    editLoading.value = false
  }
}

const confirmDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除角色「${row.roleName}」吗？`,
    '删除确认',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteAdminRole(row.roleId)
      if (res && res.code === 200) {
        ElMessage.success(res.message || '角色删除成功')
        fetchRoleList()
      } else {
        ElMessage.error(res?.message || '角色删除失败')
      }
    } catch (err) {
      // 拦截器已处理401等，这里侧重业务错误提示
      ElMessage.error(err?.response?.data?.message || '删除失败')
    }
  }).catch(() => {})
}

onMounted(() => {
  fetchRoleList()
})
</script>

<style scoped>
.admin-roles {
  width: 100%;
}

.table-card {
  width: 100%;
}

.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.table-header h3 {
  margin: 0;
  font-weight: 600;
}

.meta {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
  font-size: 13px;
}

.search-input {
  width: 220px;
}

.total {
  margin-left: 8px;
}
</style> 